//
//  ToolsViewController.m
//  WisdomZhuHai
//
//  Created by JasonLee on 15/1/20.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "ToolsViewController.h"
#import "TransforController.h"
#import "TestViewController.h"
#import "PBWebViewController.h"
#import "PBSafariActivity.h"
#import "ToolBoxDetailsViewController.h"

#define CITY_CONST @"珠海"

@interface ToolsViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,retain) NSDictionary *toolDataDic;
@property (nonatomic, strong) UITableView *view_table;

@property (nonatomic, strong) NSArray *array_totalTools;
@property (nonatomic, strong) NSMutableArray *array_dataOfTools;
@property (nonatomic, strong) NSMutableArray *array_buttons;

@property (nonatomic, strong) UIView *view_weather;
@property (nonatomic, strong) UIView *view_header;

//@property (strong, nonatomic) PBWebViewController *webViewController;
@property (nonatomic,strong) ToolBoxDetailsViewController *toolDetailsList;

@end


@implementation ToolsViewController

const float ICON_WIDTH = 55;
const float ICON_HEIGHT = 55;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [[ProtocolManager shareInstance] getTools:self selector:@selector(didFinishGetToolData:)];
    [self initView];
}

- (void)initView{
    NSArray* nibView =  [[NSBundle mainBundle] loadNibNamed:@"WeatherView" owner:nil options:nil];
    self.view_weather = [(UIView *)[nibView objectAtIndex:0] retain];
    self.view_weather.frame = CGRectMake(0, 0, 320, 240);
//    self.view_weather.backgroundColor = [UIColor redColor];
    self.view_table = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    self.view_header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 568-45)];
//    self.view_weather = [[UIImageView alloc]initWithFrame:];
//    view_header.backgroundColor = [UIColor orangeColor];
    
    self.view_table.tableHeaderView = self.view_header;
    self.view_table.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    if([TransforController isTestModelOn]){
        self.view_table.delegate = self;
        self.view_table.dataSource = self;
//        self.view_table.frame = CGRectMake(0, 0, 320, 568 - 110);
    }
    [self.view addSubview:self.view_table];
}


- (void)reloadData{
//    NSURL *imgUrl = [Common getFullDownloadPathByRelativePath:@"http://203.195.140.175/okhaolvxing/Public/weather.jpg"];
//    [self.img_weather setImageWithURL:imgUrl];
//    self.view_table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 568-45) style:UITableViewStylePlain];
    [[ProtocolManager shareInstance] getToolsWithCity:CITY_CONST andTarget:self selector:@selector(didFinishGetToolData:)];
}

- (void)reloadWeather{
    
    NSDictionary *dic_weather = [self.toolDataDic objectForKey:@"weather"];
    UIImageView *img_background_weather = (UIImageView *)[self.view_weather viewWithTag:100000];
//    UIImageView *img_background_weather = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 240)];
    [self.view_weather addSubview:img_background_weather];
    NSString *imgUrl = [Common valueForKey:@"bg" dic:dic_weather];
//    NSLog(@"%s || imgUrl:%@", __FUNCTION__, imgUrl);
    [img_background_weather setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
//    [img_background_weather setImage:[UIImage imageNamed:@"member/渐变@2x.png"]];
    UILabel *lb_city = (UILabel *)[self.view_weather viewWithTag:100001];
    lb_city.text = @"珠海";
    [self.view_weather addSubview:lb_city];
    UILabel *lb_temperature = (UILabel *)[self.view_weather viewWithTag:100002];
    lb_temperature.text = [NSString stringWithFormat:@"%@°",[Common valueForKey:@"wendu" dic:dic_weather]];
    [self.view_weather addSubview:lb_temperature];
    NSArray *array_forecast = [Common valueForKey:@"forecast" dic:dic_weather];
    UILabel *lb_weather = (UILabel *)[self.view_weather viewWithTag:100003];
    lb_weather.text = [array_forecast[0] objectForKey:@"type"];
    [self.view_weather addSubview:lb_weather];
    UILabel *lb_date = (UILabel *)[self.view_weather viewWithTag:100004];
    lb_date.text = [NSString stringWithFormat:@"%@ %@",[array_forecast[0] objectForKey:@"md"], [array_forecast[0] objectForKey:@"weekday"]];
    [self.view_weather addSubview:lb_date];
    UIImageView *img_large_weather = (UIImageView *)[self.view_weather viewWithTag:100005];
    NSString *imgUrl2 = [array_forecast[0] objectForKey:@"img"];
    [img_large_weather setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl2]];
    [self.view_weather addSubview:img_large_weather];
    for(int i = 1; i <= 5; i++){
        UIImageView *img_temp = (UIImageView *)[self.view_weather viewWithTag:(100000 + i * 10 + 1)];
        NSString *url_temp = [array_forecast[i - 1] objectForKey:@"img"];
        [img_temp setImageWithURL:[Common getFullDownloadPathByRelativePath:url_temp]];
        UILabel *lb_temp2 = (UILabel *)[self.view_weather viewWithTag:(100000 + i * 10 + 2)];
        lb_temp2.text = [array_forecast[i - 1] objectForKey:@"type"];
        UILabel *lb_temp3 = (UILabel *)[self.view_weather viewWithTag:(100000 + i * 10 + 3)];
        lb_temp3.text = [array_forecast[i - 1] objectForKey:@"md"];
        [self.view_weather addSubview:img_temp];
        [self.view_weather addSubview:lb_temp2];
        [self.view_weather addSubview:lb_temp3];
    }
    [self.view_header addSubview:self.view_weather];
}

-(void)didFinishGetToolData:(NSDictionary *)dic{
    NSLog(@"%s || dic:%@", __FUNCTION__, dic);
    if(dic == nil)
    {
        NSLog(@"didFinishGetToolData dic is nil");
        return;
    }
    self.toolDataDic = dic;//从调用本方法的类中获取数据
    [self reloadWeather];//读取天气
    NSArray *list = [Common valueForKey:P_LIST dic:dic];//从获取的数据中提取tool列表
    self.array_totalTools = [NSArray arrayWithArray:list];//初始化tool数据储存组
    int temp = ([list count] / 4) + 1;//设置页面显示的tool们的行数
    self.array_buttons = [[NSMutableArray alloc]init];//初始化按钮组
    UIView *view_footer = [[UIView alloc]initWithFrame:CGRectMake(0, 175, 320, temp * 80)];
    int totalCount = 0;//声明表示当前所处理的tool的编号
    for(int i = 0; i < temp; i++){//构建一行tool
        for(int j = 0; j < 4; j++){//构建一行中每一个tool
//            NSLog(@"%s || totalCount:%d", __FUNCTION__, totalCount);
            
            if(totalCount < [list count]){
                NSDictionary *rowDic = [list objectAtIndex:totalCount];//取编号为totalCount的tool数据
                NSString *name = [Common valueForKey:P_NAME2 dic:rowDic];//取该tool的名字
                NSString *iconPath = [Common valueForKey:P_PATH2 dic:rowDic];//取该tool的图标地址
                UIView *view_temp = [[UIView alloc]initWithFrame:CGRectMake(j * 80, i * 80, 80, 80)];//构建单个tool底层画布
                
                UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(15, 5, ICON_WIDTH, ICON_HEIGHT)];//构建图标UI元件
//                view_temp.backgroundColor = [UIColor colorWithRed:((i+j)*20) / 255.0 green:((i+j)*15)/255.0 blue:((i+j)*25)/255.0 alpha:1];
                NSURL *imgUrl = [Common getFullDownloadPathByRelativePath:iconPath];//转换图标地址格式
//                NSLog(@"%s || imgURL:%@", __FUNCTION__, imgUrl);
                [imgView setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"tool/toolPlaceholder"]];//图标UI元件载入以获取的图标 #mark
                
                UILabel *lb_temp = [[UILabel alloc]initWithFrame:CGRectMake(0, 60, 80, 20)];//构建tool底部名字
                lb_temp.text = name;
                lb_temp.textAlignment = UITextAlignmentCenter;
                lb_temp.textColor = [UIColor colorWithRed:150/255.0 green:150/255.0 blue:150/255.0 alpha:1];
                lb_temp.font = [UIFont fontWithName:@"Arial" size:12.0];//设置tool名字属性
                [view_temp addSubview:lb_temp];//将tool名字放入画布
                
                UIButton *btn_temp = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];//构建按钮
                [btn_temp setAlpha:1];
                [btn_temp setTag:50000 + totalCount];//设置按钮属性
                [btn_temp addTarget:self action:@selector(toolButtonAction:) forControlEvents:UIControlEventTouchUpInside];//设置按钮动作
                [self.array_buttons addObject:btn_temp];//将按钮加入整个页面的按钮组（以统一实现本页面多个按钮动作）
                
                [view_temp addSubview:btn_temp];
                [view_temp addSubview:imgView];//将按钮和图片放入画布
                [view_footer addSubview:view_temp];//将画布放入tool组底层画布
//                NSLog(@"%s || imgName:%@ and imgUrl:%@", __FUNCTION__, name, imgUrl);
            }
            totalCount++;
        }
    }
    [self.view_table.tableHeaderView addSubview:view_footer];
}
////Version 1.0
//- (void)toolButtonAction:(id)sender{
//    UIButton *btn = (UIButton *)sender;
//    int target = btn.tag - 50000;
//    NSString *url = [NSString stringWithString:[[self.array_totalTools objectAtIndex:target] objectForKey:@"url"]];
//    NSLog(@"%s || btn_temp's tag:%d and url:%@", __FUNCTION__, target, url);
////    WebIOS *web = [[WebIOS alloc]initWithFrame:[Common shareInstance].contentFrameNoTabBar url:[Common getUrlByString:url]];
////    web.hidesBottomBarWhenPushed = YES;
////    [self.navigationCtrl pushViewController:web animated:YES];
//    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
//        self.webViewController = [[PBWebViewController alloc] init];
//        UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:0];
//        [self.webViewController.view addSubview:view_navigationBar];
//    }
//    
//    PBSafariActivity *activity = [[PBSafariActivity alloc] init];
//    self.webViewController.URL = [NSURL URLWithString:url];
//    self.webViewController.applicationActivities = @[activity];
//    self.webViewController.excludedActivityTypes = @[UIActivityTypeMail, UIActivityTypeMessage, UIActivityTypePostToWeibo];
//    
//    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
//        self.webViewController.hidesBottomBarWhenPushed = YES;
//        [self.navigationCtrl pushViewController:self.webViewController animated:YES];
//    } else {
//        [self.webViewController load];
//    }
//}
//
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//Version 2.0
- (void)toolButtonAction:(id)sender{
    UIButton *btn = (UIButton *)sender;
    int target = btn.tag - 50000;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        
        self.toolDetailsList = [[ToolBoxDetailsViewController alloc] init];
        self.toolDetailsList.toolId = [NSString stringWithFormat:@"%@",[[self.array_totalTools objectAtIndex:target] objectForKey:P_ID]];
        self.toolDetailsList.navigationItem.title = [NSString stringWithString:[[self.array_totalTools objectAtIndex:target] objectForKey:P_NAME2]];
//        UIView *view_navigationBar = [TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:0];
//        [self.toolDetailsList.view addSubview:view_navigationBar];
        self.toolDetailsList.hidesBottomBarWhenPushed = YES;
        self.toolDetailsList.navigationCtrl = self.navigationCtrl;
        [self.toolDetailsList downLoadApiData:self.toolDetailsList.toolId];
        [self.navigationCtrl pushViewController:self.toolDetailsList animated:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TestJumpCell"];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = @"前往测试模块";
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%s || indexPath:%d", __FUNCTION__, indexPath.row);
    TestViewController *testViewController = [[TestViewController alloc]init];
    testViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationCtrl pushViewController:testViewController animated:YES];
}

@end
